﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Windows.Forms;
using System.IO.Ports;
using System.Text.RegularExpressions;

using ZhimeiSoft.CharmManager.Client.Manager;
using ZhimeiSoft.CharmManager.Interface;
using ZhimeiSoft.CharmManager.DOL;
using ZhimeiSoft.Framework.Client.Utils;
using ZhimeiSoft.Framework.Client.Configuration;
using ZhimeiSoft.Framework.Client.Base;

namespace ZhimeiSoft.CharmManager.ClientForms.Control.Scheduling
{
    
    public partial class PhoneCallList : UserControl
    {
        private byte[] m_btServerReceive = new byte[10240];
        private string m_strServerReceive = string.Empty;
        /// <summary>
        /// 猫接收来电的AT命令字符串
        /// </summary>
        //private string m_showPhoneCmd = "AT+VCID=1" + "\r" + "ATS0=2" + "\r";
        private string m_showPhoneCmd = "AT+VCID=1\r | ATS0=0\r | AT+CLIP=1\r | AT+CLCC\r";// AT+CLCC\r";
        //private string m_showPhoneCmd = "AT#CID=1" + "\r";// + "ATS0=2" + "\r";
        ClientConfiguration clientConfig;

        /// <summary>
        /// 已接来电
        /// </summary>
        private DataSet dsCalled = new DataSet();
        /// <summary>
        /// 用户信息
        /// </summary>
        private DataSet dsCustomInfo = new DataSet();

        private DBEntityCustomInfo currCustomInfo = null;
        /// <summary>
        /// 返回来电显示的用户
        /// </summary>
        public DBEntityCustomInfo CustomInfo
        {
            get
            {
                return currCustomInfo;
            }
        }
        public PhoneCallList()
        {
            InitializeComponent();
            string error = string.Empty;
            if (BussinessProxyManager.Instance != null)
            {
                BussinessProxyManager.Instance.QueryCustomState(DBEntityCustomInfo.ENUM_CSTATE.C0A, out dsCustomInfo, out error);
            }

            /*
            DataTable dtCalled = new DataTable();
            //来电客户姓名
            dtCalled.Columns.Add(new DataColumn("CUSTOMNAME", typeof(System.String)));
            //来电号码
            dtCalled.Columns.Add(new DataColumn("PHONENBR", typeof(System.String)));
            //来电时间
            dtCalled.Columns.Add(new DataColumn("CALLTIME", typeof(System.DateTime)));

            dsCalled.Tables.Add(dtCalled);

            gridCtrlCalled.DataSource = dsCalled;
             */
        }

        /// <summary>
        /// 初始化Modem的通讯端口
        /// </summary>
        public void InitPort()
        {
            serialPortPhone.Close();
            richTextBox1.Clear();
            clientConfig = new ClientConfiguration();
            m_btServerReceive = new byte[10240];
            m_strServerReceive = string.Empty;
            serialPortPhone.DataReceived += new SerialDataReceivedEventHandler(serialPortPhone_DataReceived);
            if (serialPortPhone.IsOpen)
                serialPortPhone.Close();
            
            serialPortPhone.PortName = clientConfig.ComPort;
            try
            {

                serialPortPhone.Open();
                string[] modemCommand = m_showPhoneCmd.Split('|');
                foreach (string command in modemCommand)
                {
                    AppendLog("传入MODEM命令：" + command);
                    serialPortPhone.WriteLine(command);//("AT+VCID=1" + "\r");
                }
            }
            catch (Exception ex)
            {
                MsgBox.MsgInfo(ex.Message + "调制解调器端口设置错误!" + ex.Message);
            }
            finally
            {

            }
        }

        /// <summary>
        /// 串口接收数据的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void serialPortPhone_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                m_strServerReceive = serialPortPhone.ReadLine();

                //debug 测试AT命令
                this.Invoke(new MethodInvoker(delegate
                {
                    AppendLog(DateTime.Now.ToShortTimeString() + ":" + m_strServerReceive);
                }));

                if (m_strServerReceive.Trim().Equals(string.Empty))
                {
                    return;
                }

                //在主线程上增加委托事件
                this.Invoke(new MethodInvoker(delegate
                {
                    GetPhoneNumber();
                }));
            }
            catch (Exception ex)
            {
                //debug 测试AT命令
                this.Invoke(new MethodInvoker(delegate
                {
                    AppendLog(ex.Message + "\r\n" + ex.StackTrace);
                }));
            }
        }
        /// <summary>
        /// 抓取电话号码
        /// </summary>
        private void GetPhoneNumber()
        {
            AppendLog("传入数据：\r" + m_strServerReceive);
            if (m_strServerReceive.Contains("NMBR"))
            {
                Regex r = new Regex(@"NMBR\s=\s[0-9]*");
                string num = "";
                // Cycle through the matches //Match才接触
                for (Match m = r.Match(m_strServerReceive); m.Success; m = m.NextMatch())
                {
                    num = m.Value;
                }
                //去掉"NUMB = "前缀;
                num = num.Substring(7);
                //如果是程控电话则去掉第一位(代表外线近来的电话一般是9)
                if (num.Length > 11)
                {
                    num = num.Substring(1);
                }
                //处理固话-默认固话为7位
                if (num.Length < 11 && num.Length > 7)
                {
                    num = num.Substring(num.Length - 7);
                }
                DataRow[] drPhoneNumber = dsCustomInfo.Tables[0].Select("CMOBILEPHONE = '" + num + "' OR CMOBILEPHONE = '" + num + "'"
                    );

                if (drPhoneNumber.Length == 0)
                {
                    //模糊查找电话
                    drPhoneNumber = dsCustomInfo.Tables[0].Select("CMOBILEPHONE LIKE '%" + num + "%' OR CMOBILEPHONE LIKE '%" + num + "%'"
                    );
                }
                //没有登记电话
                if (drPhoneNumber.Length == 0)
                {
                    this.currCustomInfo = null;
                    ShowCustomInfo(null, num);                    
                }
                else
                {
                    DBEntityCustomInfo customInfo = new DBEntityCustomInfo(drPhoneNumber[0]);
                    this.currCustomInfo = (DBEntityCustomInfo)customInfo.Clone();
                    ShowCustomInfo(customInfo, num);
                }

                ShowNotifyWindow(Color.SteelBlue, "来电提醒", Color.Blue, "号码:" + num + "\n" + "姓名：" +"", Color.Blue, num);
            }
        }

        private void ShowCustomInfo(DBEntityCustomInfo customInfo, string phoneNumber)
        {
            if (customInfo == null)
            {
                labNickName.Text = (phoneNumber == string.Empty) ? "昵称" : "昵称：未知";
                labName.Text = (phoneNumber == string.Empty) ? "会员姓名" : "会员姓名：未知";
                labPhone.Text = (phoneNumber == string.Empty) ? "电话号码" : "电话号码：" + phoneNumber;
                labLastRegisterDate.Text = "最后一次到店";
                labLastCallDate.Text = "最后一次回访";
                this.currCustomInfo = null;
            }
            else
            {
                labNickName.Text = "昵称：" + customInfo.CNICKNAME;
                labName.Text = "会员姓名：" + customInfo.CNAME;
                labPhone.Text = "电话号码：" + customInfo.CMOBILEPHONE;
                labLastRegisterDate.Text = "最后一次到店：" + customInfo.CLASTREGISTERDATE.ToShortDateString();
                labLastCallDate.Text = "最后一次回访：" + customInfo.CLASTCALL.ToShortDateString();
            }
        }
        /// <summary>
        /// 右下角来电提醒窗体
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="conent">内容</param>
        public void ShowNotifyWindow(Color backColor, string title, Color titleColor, string conent, Color textColor, string phoneID)
        {
            NotifyWindow nw;
            nw = new NotifyWindow(title, conent);
            //nw.TitleClicked += new System.EventHandler(titleClick);
            nw.TextClicked += new System.EventHandler(textClick);
            nw.WaitTime = 86400000;  //设置来电提示窗体等待时间为24小时;
            int width = 130;
            int height = 110;
            nw.TitleFont = new Font("黑体", 12, FontStyle.Bold);
            nw.Tag = phoneID;
            nw.SetDimensions(width, height);
            nw.TitleColor = titleColor;
            nw.TextColor = textColor;
            nw.BackColor = backColor;
            nw.Notify();

        }

        private void AppendLog(string log)
        {
            if (richTextBox1.Visible)
            {
                richTextBox1.AppendText(DateTime.Now.ToShortTimeString() + ":" + log);
            }
        }

        protected void textClick(object sender, System.EventArgs e)
        {
            //titleClick(sender, e);
        }


        private void btnSetPort_Click(object sender, EventArgs e)
        {
            serialPortPhone.Close();
            richTextBox1.Clear();
            frmSetComPort frmComPort = new frmSetComPort();
            if (frmComPort.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

        }

        private void btnStartCall_Click(object sender, EventArgs e)
        {
            if (btnStartCall.Text.Equals("开始"))
            {
                //开始电话监听
                this.InitPort();
                timer1.Enabled = true;
                btnStartCall.Text = "停止";
            }
            else
            {
                labelTime.Text = "当前时间";
                timer1.Enabled = false;
                serialPortPhone.Close();
                btnStartCall.Text = "开始";
            }
        }

        private void labLastCallDate_DoubleClick(object sender, EventArgs e)
        {
            richTextBox1.Visible = !richTextBox1.Visible;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            labelTime.Text = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString();
            
        }

        private void timerClear_Tick(object sender, EventArgs e)
        {
            //三分钟自动重置
            ShowCustomInfo(null, string.Empty);
        }


        
    }
}
